package com.xinghou.platform.server.api.controller;

import com.xinghou.platform.dao.bases.redis.RedisOperator;
import com.xinghou.platform.dao.main.AreaCodeDAO;
import com.xinghou.platform.entity.req.ListReq;
import com.xinghou.platform.entity.req.UserRegistReq;
import com.xinghou.platform.entity.resp.UserInfoResp;
import com.xinghou.platform.entity.resp.UserRegistResp;
import com.xinghou.platform.model.main.AreaCode;
import com.xinghou.platform.model.main.TempArea;
import com.xinghou.platform.model.main.UserSignatures;
import com.xinghou.platform.server.api.bussiness.MsgInfoBusinessService;
import com.xinghou.platform.server.api.bussiness.UserInfoBusinessService;
import com.xinghou.platform.server.api.log.ApiLogger;
import com.xinghou.platform.server.api.log.LoggerFactory;
import com.xinghou.platform.service.main.UserService;
import com.xinghou.platform.util.*;
import com.xinghou.platform.util.exception.DBExceptionEnums;
import com.xinghou.platform.util.exception.ServiceException;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class UserInfoController extends BaseControl {

    @Resource
    private UserInfoBusinessService userInfoBusinessService;


    @Resource
    private MsgInfoBusinessService msgInfoBusinessService;
    @Resource
    private AreaCodeDAO areaCodeDAO;

/*
   private UserRegistResp userRegistResp;
    private UserInfoResp userInfoResp;*/

    private String reqjson;//请求json
    private String repjson;//返回json

    private String key = ConfigUtil.getProperty("HTTP_SERVICE_KEY");
    private String mobileurl = ConfigUtil.getProperty("MOBILE_URL");
    private String mobileaccount = ConfigUtil.getProperty("MOBILE_ACCOUNT");
    private String mobilepwd = ConfigUtil.getProperty("MOBILE_PWD");

    private boolean bool = true;

    private Logger logInfo = LoggerFactory.getServerInfoLogger(UserInfoController.class);


    @ResponseBody
    @RequestMapping(value="/xhadh5",method = {RequestMethod.GET,RequestMethod.POST})
    public String xhadh5(@RequestBody UserRegistReq userRegistReq)
    {
        String code=userInfoBusinessService.getxhh5code(null);
        HashMap map=new HashMap();
        map.put("code",code);
        return response(map);
    }
    /**
     * 用户登入验证
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logincheck", method = {RequestMethod.POST})
    public String loginCheck( @RequestBody UserRegistReq userRegistReq,
                             HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();

        if(!"MOBILE".equals(userRegistReq.getType())){
            //第三方登陆 判断用户是否存在，如果不存在先去绑定
            userInfoBusinessService.processUserInfoOther(userRegistReq);
        }

        UserInfoResp userInfoResp = userInfoBusinessService.getUserInfo(userRegistReq);
        if (userInfoResp != null) {
            userRegistReq.setUserid(userInfoResp.getUserid());
            userInfoBusinessService.updateUserLocation(userRegistReq);
            userRegistResp.setUserid(userInfoResp.getUserid());
            userRegistResp.setRegstatus(userInfoResp.getRegstatus());
            String token = UUID.randomUUID().toString();
            HttpSession session = request.getSession();
            session.setAttribute("token", token);
            userRegistResp.setToken(token);
        }else{
            throw new ServiceException(DBExceptionEnums.USER_NO_EXISTS);
        }
        repjson = JsonUtil.toJson(userInfoResp);
        return response(userInfoResp);
    }

    /**
     * 用户发布个人标签
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pubSignature", method = {RequestMethod.POST})
    public String pubSignature( @RequestBody UserRegistReq userRegistReq,
                               HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        userInfoBusinessService.updateUserInfoBase(userRegistReq);
        repjson = JsonUtil.toJson(userRegistResp);
        return response(userRegistResp);
    }

   /**
    * 创建账户
    *
    * @param userRegistReq
    * @param request
    * @param response
    * @return
    */
    @ResponseBody
    @RequestMapping(value = "/regAccount", method = {RequestMethod.POST})
    public String createAccount( @RequestBody UserRegistReq
                                         userRegistReq,
                                 HttpServletRequest request, HttpServletResponse response) {
        String mobile = userRegistReq.getMobile();
        if(!"MOBILE".equals(userRegistReq.getType())){
            throw new ServiceException(DBExceptionEnums.MOILETYPE_ERROR);
        }
        if(StringUtils.isBlank(mobile)){
            throw new ServiceException(DBExceptionEnums.MOBILE_IS_ALREADY_EXIT);
        }
        if(userInfoBusinessService.isMobileBind(mobile)){
            throw new ServiceException(DBExceptionEnums.MOBILE_IS_ALREADY_EXIT);
        }
        userInfoBusinessService.processUserMobile(userRegistReq);
        return response(null);
    }


 /*   *//**
     * 创建账户
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     *//*
    @ResponseBody
    @RequestMapping(value = "/regAccount", method = {RequestMethod.POST})
    public String createAccount( @RequestBody UserRegistReq
            userRegistReq,
                                HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        int userid=0;
            userRegistResp.setResult("0");
            UserInfoResp userInfoResp = userInfoBusinessService.getUserInfo(userRegistReq);
            if (userInfoResp != null) {
                userRegistResp.setCkresult("1");
                userRegistResp.setErrcode("0");
                userRegistResp.setErrmsg("mobile:" + userInfoResp.getMobile() == null ? userInfoResp.getMobile() : "" + " has bind this account");
            } else {
                userid = userInfoBusinessService.createUserAccount(userRegistReq);
                if (userid > 0) {

                    userRegistResp.setCkresult("0");
                    userRegistResp.setUserid(String.valueOf(userid));
                    String token = UUID.randomUUID().toString();
                    userRegistResp.setToken(token);
                    userRegistResp.setErrcode("0");
                    userRegistResp.setErrmsg("success");

                } else {
                    throw new ServiceException(DBExceptionEnums.SERVER_INTEERFACE_ERROR);
                }
            }


        repjson = JsonUtil.toJson(userRegistResp);

        logInfo.info("/regAccount:rep" + repjson);

        return response(null);
    }
*/
    /**
     * 添加基本信息
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/regInfo", method = {RequestMethod.POST})
    public String regUserInfo( @RequestBody UserRegistReq userRegistReq,
                              HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        if(userRegistReq.getUserid()==null&&userRegistReq.getMobile()!=null&&userRegistReq.getPwd()!=null) {
            userInfoBusinessService.updateUserPassword(userRegistReq);
        }else {
            userInfoBusinessService.updateUserInfoBase(userRegistReq);
        }
        repjson = JsonUtil.toJson(userRegistResp);
        logInfo.info("/regInfo:rep" + repjson);
        return response(userRegistResp);

    }

    /**
     * 添加用户兴趣
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/regTaste", method = {RequestMethod.POST})
    public String regUserTaste(@RequestBody UserRegistReq
            userRegistReq,
                               HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        String result = userInfoBusinessService.updateUserInfoTaste(userRegistReq);
        repjson = JsonUtil.toJson(userRegistResp);
        logInfo.info("/regTaste:rep" + repjson);
        return response(userRegistResp);
    }


    @ResponseBody
    @RequestMapping(value = "/searchUserByKey", method = {RequestMethod.POST, RequestMethod.GET})
    public String searchUserByKey( @RequestBody UserRegistReq
            userRegistReq,
                                HttpServletRequest request, HttpServletResponse response) {
        Integer pageno=Integer.parseInt(userRegistReq.getPageno());
        Integer pagesize=Integer.parseInt(userRegistReq.getPagesize());
        List<UserInfoResp> userInfoList=userInfoBusinessService.searchUserByKey(Integer.parseInt(userRegistReq.getUserid()), userRegistReq.getFindkey(), pageno, pagesize);
        repjson = JsonUtil.toJson(userInfoList);
        logInfo.info("/findAccountInfo:rep" + repjson);
       return  response(userInfoList);

    }

    @ResponseBody
    @RequestMapping(value = "/searchUsers", method = {RequestMethod.POST, RequestMethod.GET})
    public String searchUsers( @RequestBody UserRegistReq
            userRegistReq,
                                  HttpServletRequest request, HttpServletResponse response) {
        List<UserInfoResp> userInfoList=userInfoBusinessService.searchUsers(userRegistReq);
        if(userInfoList==null)userInfoList=new ArrayList<UserInfoResp>();
        repjson = JsonUtil.toJson(userInfoList);
        logInfo.info("/findAccountInfo:rep" + repjson);
        return  response(userInfoList);

    }



    @ResponseBody
    @RequestMapping(value = "/genareacode", method = {RequestMethod.POST, RequestMethod.GET})
    public void generareacode(@RequestBody UserRegistReq
            userRegistReq,
                                HttpServletRequest request, HttpServletResponse response) {

        List<AreaCode> provinces=areaCodeDAO.getAreaCodesByLevel("province");
        List<TempArea> tempAreas=new ArrayList<TempArea>();

        for(int i=0;i<provinces.size();i++)
        {
            TempArea area=new TempArea();
            area.areacode=provinces.get(i).getAdcode();
            area.areaname=provinces.get(i).getProvince();
            String code=provinces.get(i).getAdcode();
            List<AreaCode> citys=areaCodeDAO.getSubAreaByAdcode(code);
            List<TempArea> subareas=new ArrayList<TempArea>();
            for(int j=0;j<citys.size();j++)
            {
                TempArea t=new TempArea();
                t.areacode=citys.get(j).getAdcode();
                if("city".equals(citys.get(j).getLevel())){
                    t.areaname=citys.get(j).getCity();
                }
                else
                    t.areaname=citys.get(j).getDistrict();
                subareas.add(t);
            }
            area.citys=subareas;
            tempAreas.add(area);
        }
        String json=JsonUtil.toJson(tempAreas);
        response(tempAreas);
        System.out.println(json);



    }


    @ResponseBody
    @RequestMapping(value = "/getUsersSigns", method = {RequestMethod.POST, RequestMethod.GET})
    public String getUserSignatures( @RequestBody UserRegistReq
            userRegistReq, HttpServletRequest request, HttpServletResponse response) {
        List<UserInfoResp> userInfoList=null;
        userInfoList= userInfoBusinessService.getUsersSignatures(userRegistReq.getIds());
                logInfo.info("/findAccountInfo:rep" + repjson);
        return response(userInfoList);
    }

    @ResponseBody
    @RequestMapping(value = "/getFollows", method = {RequestMethod.POST, RequestMethod.GET})
    public String getUserFollows( @RequestBody UserRegistReq
            userRegistReq, HttpServletRequest request, HttpServletResponse response) {
        Integer pageno=Integer.parseInt(userRegistReq.getPageno());
        Integer pagesize=Integer.parseInt(userRegistReq.getPagesize());
        List<UserInfoResp> userInfoList=null;
        if("1".equals(userRegistReq.getType())) {
            userInfoList  =userInfoBusinessService.getFollowUsers(Integer.parseInt(userRegistReq.getUserid()),pageno,pagesize);
        }
        else{
            userInfoList = userInfoBusinessService.getFanUsers(Integer.parseInt(userRegistReq.getUserid()),pageno,pagesize);
        }
        if(userInfoList==null) userInfoList=new ArrayList<UserInfoResp>();
        logInfo.info("/findAccountInfo:rep" + repjson);
        return response(userInfoList);
    }



    /**
     * 第三方信息获取
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserInfoOther", method = {RequestMethod.POST})
    public String getUserInfoOther(@RequestBody UserRegistReq
            userRegistReq,
                                   HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();


            userInfoBusinessService.processUserInfoOther(userRegistReq);
            userRegistResp.setErrcode("0");
            userRegistResp.setErrmsg("success");


        repjson = JsonUtil.toJson(userRegistResp);

        logInfo.info("/getUserInfoOther:rep" + repjson);

        return response(userRegistResp);

    }

    /**
     * 发送手机号验证码
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/checkMobile", method = {RequestMethod.POST})
    public String checkMobile( @RequestBody UserRegistReq userRegistReq,
                              HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserRegistResp userRegistResp=new UserRegistResp();
        String rnum = RandomNumber.getRandomString(4, true);
        String mobile = userRegistReq.getMobile();
        int count =  userInfoBusinessService.getCheckMobileCount(mobile);
        //需要增加发送手机验证码方法
        if (rnum != null&& count<=10) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("account", mobileaccount);
            map.put("pswd", mobilepwd);
            map.put("mobile", mobile);
            map.put("msg", "您的验证码：" + rnum + "，10分钟内有效。如非本人操作，请忽略【星后】");
            map.put("needstatus", "true");
            HttpUtils.URLPost(mobileurl, map);
            userRegistResp.setCheckno(rnum);
        }else{
            throw new ServiceException(DBExceptionEnums.MOILECHECK_ERROR);
        }
        repjson = JsonUtil.toJson(userRegistResp);
        logInfo.info("/checkMobile:rep" + repjson);
        return response(userRegistResp);
    }

    /**
     * 更新手机号
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateMobile", method = {RequestMethod.POST})
    public String updateMobile( @RequestBody UserRegistReq
            userRegistReq,
                               HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        UserInfoResp userInfoResp = null;
        userRegistResp.setResult("0");
        if (StringUtils.isBlank(userRegistReq.getMobile())) {
            throw new ServiceException(DBExceptionEnums.MOBILE_IS_NULL);
        } else if (StringUtils.isBlank(userRegistReq.getPwd())) {
            throw new ServiceException(DBExceptionEnums.PASSWORD_IS_ERROR);
        } else if (StringUtils.isBlank(userRegistReq.getUserid())) {
            throw new ServiceException(DBExceptionEnums.USER_IS_NULL);
        }
        userRegistReq.setType("mobile");
        userInfoResp = userInfoBusinessService.getUserInfo(userRegistReq);
        if (userInfoResp == null)
            throw new ServiceException(DBExceptionEnums.USER_IS_NULL);
            userInfoBusinessService.updateUserMobile(userRegistReq);
        repjson = JsonUtil.toJson(userRegistResp);
        logInfo.info("/updateMobile:rep" + repjson);
        return response(userRegistResp);

    }

    /**
     * 更新用户个人签名
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSignatures", method = {RequestMethod.POST})
    public String updateSignatures( @RequestBody UserRegistReq
            userRegistReq,
                                   HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp=new UserRegistResp();
        UserSignatures signatures = new UserSignatures();
        signatures.uid = Integer.parseInt(userRegistReq.getUserid());
        signatures.signatures = userRegistReq.getSignatures();
        userInfoBusinessService.pubSignatures(signatures);

        repjson = JsonUtil.toJson(userRegistResp);

        logInfo.info("/updateSignatures:rep" + repjson);

        return response(userRegistResp);

    }


    /**
     * 更新用户个人介绍
     *
     * @param userRegistReq
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateIntr", method = {RequestMethod.POST})
    public String updateIntr(@RequestBody UserRegistReq
            userRegistReq,
                             HttpServletRequest request, HttpServletResponse response) {
        UserRegistResp userRegistResp = new UserRegistResp();
          if (StringUtils.isBlank(userRegistReq.getUserid())) {
            bool = false;
            throw new ServiceException(DBExceptionEnums.USER_IS_NULL);
        } else {
            bool = true;
        }

        if (bool) {
            if (userInfoBusinessService.updateSignatures(userRegistReq) == 0) {
                userRegistResp.setCkresult("0");
                userRegistResp.setErrcode("0");
                userRegistResp.setErrmsg("success");
            } else {
                throw new ServiceException(DBExceptionEnums.UPDATE_ERROR);
            }
        }


        repjson = JsonUtil.toJson(userRegistResp);

        logInfo.info("/updateSignatures:rep" + repjson);

        return response(userRegistResp);

    }






    /**
     * 判断手机号码是否注册
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/mobileExist", method = {RequestMethod.POST})
    public String mobileExist( @RequestBody UserRegistReq
            userRegistReq,
                              HttpServletRequest request, HttpServletResponse response) {

        String mobile = userRegistReq.getMobile();
        if(StringUtils.isBlank(mobile)){
            throw new ServiceException(DBExceptionEnums.MOBILE_IS_ALREADY_EXIT);
        }
            return response(userInfoBusinessService.isMobileBind(mobile));
   /*UserRegistResp userRegistResp = new UserRegistResp();
    ApiLogger.log("/mobileExist", userRegistReq);
        SignUtil.checkRequestJson(userRegistReq);
        String phonenumber = userRegistReq.getMobile();
        if (null == phonenumber || phonenumber.length() < 1) {
            throw new ServiceException(DBExceptionEnums.MOBILE_IS_NOT_LEGAL);
        } else {
            int ret = userInfoBusinessService.mobileExist(phonenumber, userRegistReq.getType(), userRegistReq.getSecondaccount());
            userRegistResp.setCkresult(String.valueOf(ret));
            userRegistResp.setErrcode("0");
            userRegistResp.setErrmsg("success");
        }
        repjson = JsonUtil.toJson(userRegistResp);
        logInfo.info("/mobileExist:rep" + repjson);*/

    }



    /**
     * 获取随机用户
     * @param sex
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRandomUser", method = {RequestMethod.GET})
    public String getRandomUser(@RequestParam Integer sex,
                                HttpServletRequest request, HttpServletResponse response) {
        ApiLogger.log("/getRandomUser", sex);
        // SignUtil.checkRequestJson(sex);
        String uid =userInfoBusinessService.getRandomUser(sex);
        return response(uid);
    }

    /**
     * 获取用户列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userList", method = {RequestMethod.POST})
    public String userList( @RequestBody ListReq
                                       listReq,
                               HttpServletRequest request, HttpServletResponse response) {

        List<UserInfoResp> list= userInfoBusinessService.userList(listReq);
        logInfo.info("/userList:rep" + repjson);
        return response(list);
    }

    /**
     * 封禁用户
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/closureUser", method = {RequestMethod.POST})
    public String closureUser( @RequestBody ListReq
                                       listReq,
                               HttpServletRequest request, HttpServletResponse response) {

        userInfoBusinessService.closureUser(listReq);
        return response(null);
    }

    /**
     * 解封用户
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/unclosureUser", method = {RequestMethod.POST})
    public String unclosureUser( @RequestBody ListReq
                                       listReq,
                               HttpServletRequest request, HttpServletResponse response) {

        userInfoBusinessService.unclosureUser(listReq);
        return response(null);
    }


    /**
     * 根据用户id获取头像和昵称
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getHeadAndNameById", method = {RequestMethod.POST})
    public String getHeadAndNameById( @RequestBody  UserRegistReq
                                                  userRegistReq,
                                 HttpServletRequest request, HttpServletResponse response) {

        List<UserInfoResp> list= userInfoBusinessService.getHeadAndNameById(userRegistReq.getIds());
        return response(list);
    }



    /**
     * 根据用户id获取头像和昵称
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLastThreeDayData")
    public String getLastThreeDayData( HttpServletRequest request, HttpServletResponse response) {
        List<String> list= userInfoBusinessService.getLastThreeDayData();
        return response(list);
    }




    public String getReqjson() {
        return reqjson;
    }

    public void setReqjson(String reqjson) {
        this.reqjson = reqjson;
    }

    public String getRepjson() {
        return repjson;
    }

    public void setRepjson(String repjson) {
        this.repjson = repjson;
    }

}
